﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.BasicList
{
    public partial class panel_IQ : UserControl
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        private SqlConnection masterConnection;
        
        public panel_IQ()
        {
            InitializeComponent();

            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.masterConnection = new SqlConnection(mySetting.DB2ConnectionString);

            LoadData();

            this.IQ.DoubleClick += IQ_DoubleClick;
            this.IQ.PopupMenuShowing += IQ_PopupMenuShowing;
            this.IQContext.ItemClicked += IQContext_ItemClicked;
        }

        private void callEditForm()
        { 
            DataRow row = IQ.GetFocusedDataRow();
            frm_Edit_IQ editForm = new frm_Edit_IQ();
            editForm.iq_id = row[0].ToString();
            if (editForm.LoadData())
            {                
                editForm.ShowDialog();
                LoadData();
            }
            else
            {
                MessageBox.Show("Cannot load data for selected record");
            } 
        }

        void IQ_DoubleClick(object sender, EventArgs e)
        {
            callEditForm(); 
        }

        void IQContext_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            this.IQContext.Hide();            
            switch (e.ClickedItem.Name)
            {
                case "importSelection":
                    importDatabase();
                    break;
                case "addSelection":
                    frm_Add_IQ add_form = new frm_Add_IQ();
                    add_form.ShowDialog();
                    break;
                case "editSelection":
                    callEditForm();
                    break;
                case "deleteSelection":
                    deleteRecord();
                    break;
                case "refreshSelection":
                    LoadData();
                    break;
            }
        }

        void IQ_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            this.IQContext.Show(MousePosition);
        }

        ///////////////////////////////////
        /// Load Data From Local Database
        ///////////////////////////////////
        private void LoadData()
        {
            DataSet sourceDataSet = new DataSet();
            INISettings mySettings = new INISettings();
            SQLManagement mySQLManagement = new SQLManagement();
            mySQLManagement.SQLConnectionString = mySettings.SQLConnectionString;
            string sql = "SELECT [IQID], [VietnameseName], [EnglishName], [IQDate], [ProfileCode], [Quantity], [UnitID],"
                + " [NVLC], [ImOrEx], [Limited]"
                + " FROM [222_IQ]";
            sourceDataSet = mySQLManagement.SQL_Query(sql);
            if (sourceDataSet != null)
            {
                gridIQ.DataSource = sourceDataSet.Tables[0];
                getUpdateInfo();
            }
            else
            {
                MessageBox.Show("There is no data for IQ");
                DataTable newTable = new DataTable();
                newTable.Columns.Add("IQID", typeof(string));
                newTable.Columns.Add("VietnameseName", typeof(string));
                newTable.Columns.Add("EnglishName", typeof(string));
                newTable.Columns.Add("IQDate", typeof(DateTime));
                newTable.Columns.Add("ProfileCode", typeof(string));
                newTable.Columns.Add("Quantity", typeof(int));
                newTable.Columns.Add("UnitID", typeof(string));
                newTable.Columns.Add("NVLC", typeof(bool));
                newTable.Columns.Add("ImOrEx", typeof(bool));
                newTable.Columns.Add("Limited", typeof(bool));
                gridIQ.DataSource = newTable;
            }
            IQ.Columns[0].Caption = "IQ ID";
            IQ.Columns[1].Caption = "Vietnamese Name";
            IQ.Columns[2].Caption = "English Name";
            IQ.Columns[3].Caption = "IQ Date";
            IQ.Columns[4].Caption = "Profile Code";
            IQ.Columns[5].Caption = "Quantity";
            IQ.Columns[6].Caption = "Unit ID";
            IQ.Columns[7].Caption = "NVLC";
            IQ.Columns[8].Caption = "Import or Export";
            IQ.Columns[9].Caption = "Limited";
            IQ.BestFitColumns();
        }

        /////////////////////////////////////
        /// Get Update Information
        /////////////////////////////////////
        private void getUpdateInfo()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT LastUpdate FROM [222_UpdateHistory] WHERE ID=15";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    this.updateDate.Text = dataReader["LastUpdate"].ToString();
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get update information");
            }
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            LoadData();
        }


        private void buttonEdit_Click(object sender, EventArgs e)
        {
            callEditForm(); 
        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            importDatabase();
        }

        ////////////////////////////////////
        /// Update database From AS400
        ////////////////////////////////////
        private void importDatabase()
        { 
            DataSet as400 = new DataSet();
            DataSet iq = new DataSet();
            string sql = null;
            SqlCommand cmd;
            SqlDataAdapter adapter;
            DataTable iq_db2;
            DataTable iq_local;                
            try
            {
                //Get Data From AS400                
                masterConnection.Open();
                sql = "SELECT * FROM OPENQUERY(AS400_MPFLIB, 'SELECT IQNO, IQPNAM, IQUPDT FROM MPIQ00')";
                cmd = new SqlCommand(sql, masterConnection);
                adapter = new SqlDataAdapter();
                adapter.SelectCommand = cmd;
                adapter.Fill(as400);
                iq_db2 = as400.Tables[0];
                adapter.Dispose();
                cmd.Dispose();
                masterConnection.Close(); 
                
                //Get Data From Local Database
                myConnection.Open();
                sql = "SELECT * FROM [222_IQ]";
                cmd = new SqlCommand(sql, myConnection);
                adapter = new SqlDataAdapter();
                adapter.SelectCommand = cmd;
                adapter.Fill(iq, "222_IQ");
                iq_local = iq.Tables["222_IQ"];
                                
                foreach (DataRow as400_row in iq_db2.Rows)
                {
                    DataRow[] current_row = iq_local.Select("IQID='" + as400_row["IQNO"].ToString() + "'");
                    if (current_row.Length > 0)
                    {
                        foreach (DataRow local_row in current_row)
                        {
                            local_row.BeginEdit();
                            local_row["EnglishName"] = as400_row["IQPNAM"].ToString();
                            local_row["IQDate"] = as400_row["IQUPDT"].ToString();                            
                            local_row.EndEdit();
                        }
                    }
                    else
                    {
                        DataRow new_row = iq_local.NewRow();
                        new_row["IQID"] = as400_row["IQNO"].ToString();
                        new_row["EnglishName"] = as400_row["IQPNAM"].ToString();
                        new_row["IQDate"] = as400_row["IQUPDT"].ToString();
                        new_row["UnitID"] = "No";
                        iq_local.Rows.Add(new_row);
                    }
                }  
                               

                SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(adapter);
                //Update to Local Database
                adapter.Update(iq, "222_IQ");
                
                adapter.Dispose();
                cmd.Dispose();
                myConnection.Close();
                
                //Update History
                myConnection.Open();
                sql = "UPDATE [222_UpdateHistory] SET LastUpdate=GETDATE() WHERE ID=15";
                SqlCommand cmd_sql = new SqlCommand(sql, myConnection);                
                cmd_sql.ExecuteNonQuery();
                cmd_sql.Dispose();
                myConnection.Close();

                LoadData();

                MessageBox.Show("Database has been updated successfull.");
                                
            }
            catch (Exception ex)
            {
                if (masterConnection.State == ConnectionState.Open)
                {
                    masterConnection.Close();
                }

                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show(ex.Message);
                //MessageBox.Show("Cannot connect to AS400");
            } 
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            frm_Add_IQ add_form = new frm_Add_IQ();
            add_form.ShowDialog();
            LoadData();
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            deleteRecord();
        }

        private void deleteRecord()
        {
            if (MessageBox.Show("Are you really to delete selected record now?", "Confirm delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                DataRow row = IQ.GetFocusedDataRow();
                try
                {
                    myConnection.Open();
                    string sql = "DELETE [222_IQ] WHERE IQID='" + row[0].ToString() + "'";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("IQ deleted success.");
                    LoadData();
                }
                catch //(Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    //MessageBox.Show(ex.Message);
                    MessageBox.Show("Cannot delete IQ. Please try again.");
                }
            }
        }
    }
}
